package com.yuantu.judiciary.aop;

import com.alibaba.fastjson2.JSON;

import com.wechat.pay.java.core.http.HttpMethod;
import com.yuantu.judiciary.annotation.Log;
import com.yuantu.judiciary.manager.AsyncManager;
import com.yuantu.judiciary.manager.factory.AsyncFactory;
import com.yuantu.judiciary.model.domain.SysPlatformOperateLogDO;
import com.yuantu.judiciary.model.dto.AccountInfoDTO;
import com.yuantu.judiciary.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import org.springframework.core.NamedThreadLocal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Map;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Slf4j
@Aspect
@Component
public class SysPlatformLogAspect {

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }


    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前的用户
            Long accountId = getCurrentAccountId();
            // *========数据库日志=========*//
            SysPlatformOperateLogDO operLog = new SysPlatformOperateLogDO();
            // 获取请求路径
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
            operLog.setOperatorIp(httpServletRequest.getRemoteHost());
            operLog.setOperatorId(accountId);
            operLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog, httpServletRequest);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordSysPlatformOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
        }
    }


    /**
     * 获取当前账号 id
     */
    public Long getCurrentAccountId() {
        try {
            if (ObjectUtils.isEmpty(SecurityContextHolder.getContext())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
            ) {
                return null;
            } else {
                AccountInfoDTO accountInfo = (AccountInfoDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                return accountInfo.getAccountId();
            }
        } catch (Exception e) {
//            log.error("获取当前账号 id 失败: " + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysPlatformOperateLogDO operLog,
                                               HttpServletRequest request) throws Exception {
        // 设置标题
        operLog.setDescription(log.title());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog, request);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, SysPlatformOperateLogDO operLog, HttpServletRequest request) throws Exception {
        String method = request.getMethod();
        Map<?, ?> paramsMap = request.getParameterMap();
        if (HttpMethod.PUT.name().equals(method) || HttpMethod.POST.name().equals(method)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperatorParam(params);
        } else {
            operLog.setOperatorParam(JSON.toJSONString(paramsMap));
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!ObjectUtils.isEmpty(o) && !isFilterObject(o)) {
                    try {
                        String jsonObj = JSON.toJSONString(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }


    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }
}
